{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 38,
   "metadata": {
    "collapsed": true
   },
   "outputs": [
    {
     "ename": "SyntaxError",
     "evalue": "invalid syntax (4224584999.py, line 3)",
     "output_type": "error",
     "traceback": [
      "\u001B[1;36m  Cell \u001B[1;32mIn [38], line 3\u001B[1;36m\u001B[0m\n\u001B[1;33m    1 2 3 4 5 6\u001B[0m\n\u001B[1;37m      ^\u001B[0m\n\u001B[1;31mSyntaxError\u001B[0m\u001B[1;31m:\u001B[0m invalid syntax\n"
     ]
    }
   ],
   "source": [
    "# Notebook的魔法指令，相当于写了一个文件\n",
    "%%writefile tang.txt\n",
    "1 2 3 4 5 6\n",
    "2 3 5 8 7 9\n",
    "# 可以看一下本地是否创建出了这样一个文件"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "outputs": [],
   "source": [
    "import numpy as np"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "如果用Python来读取数据，看起来有点麻烦："
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "outputs": [
    {
     "data": {
      "text/plain": "array([[1., 2., 3., 4., 5., 6.],\n       [2., 3., 5., 8., 7., 9.]])"
     },
     "execution_count": 40,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "data=[]\n",
    "with open('tang.txt') as f:\n",
    "    for line in f.readlines():\n",
    "        fileds =line.split()\n",
    "        cur_data=[float(x) for x in fileds]\n",
    "        data.append(cur_data)\n",
    "data=np.array(data)\n",
    "data"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "outputs": [
    {
     "data": {
      "text/plain": "array([[1., 2., 3., 4., 5., 6.],\n       [2., 3., 5., 8., 7., 9.]])"
     },
     "execution_count": 41,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Numpy只需要一行就完成上述操作\n",
    "data=np.loadtxt('tang.txt')\n",
    "data"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Writing tang2.txt\n"
     ]
    }
   ],
   "source": [
    "%%writefile tang2.txt\n",
    "1,2,3,4,5,6\n",
    "2,3,5,8,7,9"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "outputs": [
    {
     "data": {
      "text/plain": "array([[1., 2., 3., 4., 5., 6.],\n       [2., 3., 5., 8., 7., 9.]])"
     },
     "execution_count": 42,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 读取的时候也需要指定好分隔符\n",
    "data = np.loadtxt('tang2.txt',delimiter=',')\n",
    "data"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Writing tang3.txt\n"
     ]
    }
   ],
   "source": [
    "%%writefile tang3.txt\n",
    "x,y,z,w,a,b\n",
    "1,2,3,4,5,6\n",
    "2,3,5,8,7,9"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "outputs": [
    {
     "data": {
      "text/plain": "array([[1., 2., 3., 4., 5., 6.],\n       [2., 3., 5., 8., 7., 9.]])"
     },
     "execution_count": 45,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 可以指定去掉前几行\n",
    "data = np.loadtxt('tang3.txt',delimiter=',',skiprows=1)\n",
    "data"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Help on function loadtxt in module numpy:\n",
      "\n",
      "loadtxt(fname, dtype=<class 'float'>, comments='#', delimiter=None, converters=None, skiprows=0, usecols=None, unpack=False, ndmin=0, encoding='bytes', max_rows=None, *, quotechar=None, like=None)\n",
      "    Load data from a text file.\n",
      "    \n",
      "    Each row in the text file must have the same number of values.\n",
      "    \n",
      "    Parameters\n",
      "    ----------\n",
      "    fname : file, str, pathlib.Path, list of str, generator\n",
      "        File, filename, list, or generator to read.  If the filename\n",
      "        extension is ``.gz`` or ``.bz2``, the file is first decompressed. Note\n",
      "        that generators must return bytes or strings. The strings\n",
      "        in a list or produced by a generator are treated as lines.\n",
      "    dtype : data-type, optional\n",
      "        Data-type of the resulting array; default: float.  If this is a\n",
      "        structured data-type, the resulting array will be 1-dimensional, and\n",
      "        each row will be interpreted as an element of the array.  In this\n",
      "        case, the number of columns used must match the number of fields in\n",
      "        the data-type.\n",
      "    comments : str or sequence of str or None, optional\n",
      "        The characters or list of characters used to indicate the start of a\n",
      "        comment. None implies no comments. For backwards compatibility, byte\n",
      "        strings will be decoded as 'latin1'. The default is '#'.\n",
      "    delimiter : str, optional\n",
      "        The character used to separate the values. For backwards compatibility,\n",
      "        byte strings will be decoded as 'latin1'. The default is whitespace.\n",
      "    \n",
      "        .. versionchanged:: 1.23.0\n",
      "           Only single character delimiters are supported. Newline characters\n",
      "           cannot be used as the delimiter.\n",
      "    \n",
      "    converters : dict or callable, optional\n",
      "        A function to parse all columns strings into the desired value, or\n",
      "        a dictionary mapping column number to a parser function.\n",
      "        E.g. if column 0 is a date string: ``converters = {0: datestr2num}``.\n",
      "        Converters can also be used to provide a default value for missing\n",
      "        data, e.g. ``converters = lambda s: float(s.strip() or 0)`` will\n",
      "        convert empty fields to 0.\n",
      "        Default: None.\n",
      "    \n",
      "        .. versionchanged:: 1.23.0\n",
      "           The ability to pass a single callable to be applied to all columns\n",
      "           was added.\n",
      "    \n",
      "    skiprows : int, optional\n",
      "        Skip the first `skiprows` lines, including comments; default: 0.\n",
      "    usecols : int or sequence, optional\n",
      "        Which columns to read, with 0 being the first. For example,\n",
      "        ``usecols = (1,4,5)`` will extract the 2nd, 5th and 6th columns.\n",
      "        The default, None, results in all columns being read.\n",
      "    \n",
      "        .. versionchanged:: 1.11.0\n",
      "            When a single column has to be read it is possible to use\n",
      "            an integer instead of a tuple. E.g ``usecols = 3`` reads the\n",
      "            fourth column the same way as ``usecols = (3,)`` would.\n",
      "    unpack : bool, optional\n",
      "        If True, the returned array is transposed, so that arguments may be\n",
      "        unpacked using ``x, y, z = loadtxt(...)``.  When used with a\n",
      "        structured data-type, arrays are returned for each field.\n",
      "        Default is False.\n",
      "    ndmin : int, optional\n",
      "        The returned array will have at least `ndmin` dimensions.\n",
      "        Otherwise mono-dimensional axes will be squeezed.\n",
      "        Legal values: 0 (default), 1 or 2.\n",
      "    \n",
      "        .. versionadded:: 1.6.0\n",
      "    encoding : str, optional\n",
      "        Encoding used to decode the inputfile. Does not apply to input streams.\n",
      "        The special value 'bytes' enables backward compatibility workarounds\n",
      "        that ensures you receive byte arrays as results if possible and passes\n",
      "        'latin1' encoded strings to converters. Override this value to receive\n",
      "        unicode arrays and pass strings as input to converters.  If set to None\n",
      "        the system default is used. The default value is 'bytes'.\n",
      "    \n",
      "        .. versionadded:: 1.14.0\n",
      "    max_rows : int, optional\n",
      "        Read `max_rows` rows of content after `skiprows` lines. The default is\n",
      "        to read all the rows. Note that empty rows containing no data such as\n",
      "        empty lines and comment lines are not counted towards `max_rows`,\n",
      "        while such lines are counted in `skiprows`.\n",
      "    \n",
      "        .. versionadded:: 1.16.0\n",
      "        \n",
      "        .. versionchanged:: 1.23.0\n",
      "            Lines containing no data, including comment lines (e.g., lines \n",
      "            starting with '#' or as specified via `comments`) are not counted \n",
      "            towards `max_rows`.\n",
      "    quotechar : unicode character or None, optional\n",
      "        The character used to denote the start and end of a quoted item.\n",
      "        Occurrences of the delimiter or comment characters are ignored within\n",
      "        a quoted item. The default value is ``quotechar=None``, which means\n",
      "        quoting support is disabled.\n",
      "    \n",
      "        If two consecutive instances of `quotechar` are found within a quoted\n",
      "        field, the first is treated as an escape character. See examples.\n",
      "    \n",
      "        .. versionadded:: 1.23.0\n",
      "    like : array_like, optional\n",
      "        Reference object to allow the creation of arrays which are not\n",
      "        NumPy arrays. If an array-like passed in as ``like`` supports\n",
      "        the ``__array_function__`` protocol, the result will be defined\n",
      "        by it. In this case, it ensures the creation of an array object\n",
      "        compatible with that passed in via this argument.\n",
      "    \n",
      "        .. versionadded:: 1.20.0\n",
      "    \n",
      "    Returns\n",
      "    -------\n",
      "    out : ndarray\n",
      "        Data read from the text file.\n",
      "    \n",
      "    See Also\n",
      "    --------\n",
      "    load, fromstring, fromregex\n",
      "    genfromtxt : Load data with missing values handled as specified.\n",
      "    scipy.io.loadmat : reads MATLAB data files\n",
      "    \n",
      "    Notes\n",
      "    -----\n",
      "    This function aims to be a fast reader for simply formatted files.  The\n",
      "    `genfromtxt` function provides more sophisticated handling of, e.g.,\n",
      "    lines with missing values.\n",
      "    \n",
      "    .. versionadded:: 1.10.0\n",
      "    \n",
      "    The strings produced by the Python float.hex method can be used as\n",
      "    input for floats.\n",
      "    \n",
      "    Examples\n",
      "    --------\n",
      "    >>> from io import StringIO   # StringIO behaves like a file object\n",
      "    >>> c = StringIO(\"0 1\\n2 3\")\n",
      "    >>> np.loadtxt(c)\n",
      "    array([[0., 1.],\n",
      "           [2., 3.]])\n",
      "    \n",
      "    >>> d = StringIO(\"M 21 72\\nF 35 58\")\n",
      "    >>> np.loadtxt(d, dtype={'names': ('gender', 'age', 'weight'),\n",
      "    ...                      'formats': ('S1', 'i4', 'f4')})\n",
      "    array([(b'M', 21, 72.), (b'F', 35, 58.)],\n",
      "          dtype=[('gender', 'S1'), ('age', '<i4'), ('weight', '<f4')])\n",
      "    \n",
      "    >>> c = StringIO(\"1,0,2\\n3,0,4\")\n",
      "    >>> x, y = np.loadtxt(c, delimiter=',', usecols=(0, 2), unpack=True)\n",
      "    >>> x\n",
      "    array([1., 3.])\n",
      "    >>> y\n",
      "    array([2., 4.])\n",
      "    \n",
      "    The `converters` argument is used to specify functions to preprocess the\n",
      "    text prior to parsing. `converters` can be a dictionary that maps\n",
      "    preprocessing functions to each column:\n",
      "    \n",
      "    >>> s = StringIO(\"1.618, 2.296\\n3.141, 4.669\\n\")\n",
      "    >>> conv = {\n",
      "    ...     0: lambda x: np.floor(float(x)),  # conversion fn for column 0\n",
      "    ...     1: lambda x: np.ceil(float(x)),  # conversion fn for column 1\n",
      "    ... }\n",
      "    >>> np.loadtxt(s, delimiter=\",\", converters=conv)\n",
      "    array([[1., 3.],\n",
      "           [3., 5.]])\n",
      "    \n",
      "    `converters` can be a callable instead of a dictionary, in which case it\n",
      "    is applied to all columns:\n",
      "    \n",
      "    >>> s = StringIO(\"0xDE 0xAD\\n0xC0 0xDE\")\n",
      "    >>> import functools\n",
      "    >>> conv = functools.partial(int, base=16)\n",
      "    >>> np.loadtxt(s, converters=conv)\n",
      "    array([[222., 173.],\n",
      "           [192., 222.]])\n",
      "    \n",
      "    This example shows how `converters` can be used to convert a field\n",
      "    with a trailing minus sign into a negative number.\n",
      "    \n",
      "    >>> s = StringIO('10.01 31.25-\\n19.22 64.31\\n17.57- 63.94')\n",
      "    >>> def conv(fld):\n",
      "    ...     return -float(fld[:-1]) if fld.endswith(b'-') else float(fld)\n",
      "    ...\n",
      "    >>> np.loadtxt(s, converters=conv)\n",
      "    array([[ 10.01, -31.25],\n",
      "           [ 19.22,  64.31],\n",
      "           [-17.57,  63.94]])\n",
      "    \n",
      "    Using a callable as the converter can be particularly useful for handling\n",
      "    values with different formatting, e.g. floats with underscores:\n",
      "    \n",
      "    >>> s = StringIO(\"1 2.7 100_000\")\n",
      "    >>> np.loadtxt(s, converters=float)\n",
      "    array([1.e+00, 2.7e+00, 1.e+05])\n",
      "    \n",
      "    This idea can be extended to automatically handle values specified in\n",
      "    many different formats:\n",
      "    \n",
      "    >>> def conv(val):\n",
      "    ...     try:\n",
      "    ...         return float(val)\n",
      "    ...     except ValueError:\n",
      "    ...         return float.fromhex(val)\n",
      "    >>> s = StringIO(\"1, 2.5, 3_000, 0b4, 0x1.4000000000000p+2\")\n",
      "    >>> np.loadtxt(s, delimiter=\",\", converters=conv, encoding=None)\n",
      "    array([1.0e+00, 2.5e+00, 3.0e+03, 1.8e+02, 5.0e+00])\n",
      "    \n",
      "    Note that with the default ``encoding=\"bytes\"``, the inputs to the\n",
      "    converter function are latin-1 encoded byte strings. To deactivate the\n",
      "    implicit encoding prior to conversion, use ``encoding=None``\n",
      "    \n",
      "    >>> s = StringIO('10.01 31.25-\\n19.22 64.31\\n17.57- 63.94')\n",
      "    >>> conv = lambda x: -float(x[:-1]) if x.endswith('-') else float(x)\n",
      "    >>> np.loadtxt(s, converters=conv, encoding=None)\n",
      "    array([[ 10.01, -31.25],\n",
      "           [ 19.22,  64.31],\n",
      "           [-17.57,  63.94]])\n",
      "    \n",
      "    Support for quoted fields is enabled with the `quotechar` parameter.\n",
      "    Comment and delimiter characters are ignored when they appear within a\n",
      "    quoted item delineated by `quotechar`:\n",
      "    \n",
      "    >>> s = StringIO('\"alpha, #42\", 10.0\\n\"beta, #64\", 2.0\\n')\n",
      "    >>> dtype = np.dtype([(\"label\", \"U12\"), (\"value\", float)])\n",
      "    >>> np.loadtxt(s, dtype=dtype, delimiter=\",\", quotechar='\"')\n",
      "    array([('alpha, #42', 10.), ('beta, #64',  2.)],\n",
      "          dtype=[('label', '<U12'), ('value', '<f8')])\n",
      "    \n",
      "    Two consecutive quote characters within a quoted field are treated as a\n",
      "    single escaped character:\n",
      "    \n",
      "    >>> s = StringIO('\"Hello, my name is \"\"Monty\"\"!\"')\n",
      "    >>> np.loadtxt(s, dtype=\"U\", delimiter=\",\", quotechar='\"')\n",
      "    array('Hello, my name is \"Monty\"!', dtype='<U26')\n",
      "\n",
      "None\n"
     ]
    }
   ],
   "source": [
    "print(help(np.loadtxt))"
   ],
   "metadata": {
    "collapsed": false
   }
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
